package com.wenjh.jdmzt.android.view;

import java.util.Date;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.R;
import com.wenjh.jdmzt.android.view.RefreshOnOverScrollListView.OverScrollListener;
import com.wenjh.jdmzt.util.DateUtil;

/**
 * 支持下拉刷新
 * @author wenjianhua
 *
 */
public class PulltoRefreshListView extends RefreshOnOverScrollListView implements
		OverScrollListener {
	public static final int OS_STATE_LOADING = 3;
	public static final int OS_STATE_NO_MORE_MESSAGES = 1;
	public static final int OS_STATE_PULL_DOWN_TO_LOAD = 4;
	public static final int OS_STATE_RELEASE_TO_LOAD = 2;
	private static final int HEADER_HEIGHT = 60;
	
	protected boolean mIsLoaderVisible;
	private OnPullToRefreshListener mListener;
	protected LinearLayout mLoadingContainer;
	protected ImageView loadingImageView = null;
	private boolean mNoMoreRefresh;
	protected int mOverScrollState;
	protected TextView mRefreshTimeTextView;
	protected TextView loadingTimeTextView, lodingMessageTextView;
	protected TextView mOverScrollTextView;
	protected LinearLayout mOverScrollView;
	protected RotatingImageView mOverscrollImage;
	protected RefreshOnOverScrollListView.OverScrollListener mOverscrollListener;
	protected LinearLayout mPullToRefreshTip;
	private int overScrollPadding;
	private LoadingButton loadingButton = null;
	private boolean enableLoadMoreFoolter = false;
	
	private Animation mRotateAnimation;
	static final int ROTATION_ANIMATION_DURATION = 1200;
	static final Interpolator ANIMATION_INTERPOLATOR = new LinearInterpolator();
	
	public PulltoRefreshListView(Context paramContext) {
		super(paramContext);
		this.mOverscrollListener = this;
		initRefreshOnOverscrollListView();
	}

	public PulltoRefreshListView(Context paramContext,
			AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
		this.mOverscrollListener = this;
		initRefreshOnOverscrollListView();
	}

	public PulltoRefreshListView(Context paramContext,
			AttributeSet paramAttributeSet, int paramInt) {
		super(paramContext, paramAttributeSet, paramInt);
		this.mOverscrollListener = this;
		initRefreshOnOverscrollListView();
	}

	private void initRefreshOnOverscrollListView() {
		this.mListener = null;
		
		setScrollbarFadingEnabled(true);
		setFastScrollEnabled(true);
		
		LayoutInflater inflater = AndroidKit.getLayoutInflater();
		View v = inflater.inflate(R.layout.listitem_loadmore, null);
		this.footerView = v;
		this.loadingButton = (LoadingButton) v.findViewById(R.id.btn_loading);
		
		setFooterView(v);
		showLoadMoreFoolter();
		
		setupOverscroll();
		
		mRotateAnimation = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		mRotateAnimation.setInterpolator(ANIMATION_INTERPOLATOR);
		mRotateAnimation.setDuration(ROTATION_ANIMATION_DURATION);
		mRotateAnimation.setRepeatCount(Animation.INFINITE);
		mRotateAnimation.setRepeatMode(Animation.RESTART);
	}
	
	public LoadingButton getFooterViewButton() {
		return loadingButton;
	}
	
	/**
	 * 设置是否显示一个“加载更多”的List底部栏目
	 * @param enableLoadMoreFoolter true表示显示，false反之
	 */
	public void setEnableLoadMoreFoolter(boolean enableLoadMoreFoolter) {
		this.enableLoadMoreFoolter = enableLoadMoreFoolter;
	}
	
	public void removeLoadMoreFoolter() {
		removeFooterView(footerView);
	}
	
	public void showLoadMoreFoolter() {
		if(enableLoadMoreFoolter) {
			showFooterView();
		}
	}
	
	/**
	 * 获取是否显示一个“加载更多”的List底部栏目
	 * @param enableLoadMoreFoolter
	 */
	public boolean isEnableLoadMoreFoolter() {
		return enableLoadMoreFoolter;
	}
	
	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);
		removeFooterView(footerView);
		if(/*!adapter.isEmpty() && */enableLoadMoreFoolter) {
			addFooterView(footerView);
		}
		
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
	}
	
	
	protected void setOverScrollState(int state) {
		if (state == mOverScrollState)
			return;

		switch (state) {
		case OS_STATE_NO_MORE_MESSAGES:
			mOverScrollTextView.setText(R.string.pull_to_refresh_pull_label);
			break;
		case OS_STATE_RELEASE_TO_LOAD:
			mOverScrollTextView.setText(R.string.pull_to_refresh_release_label);
			break;
		case OS_STATE_LOADING:
			mOverScrollTextView.setText(R.string.pull_to_refresh_refreshing_label);
			break;
		case OS_STATE_PULL_DOWN_TO_LOAD:
			mOverScrollTextView.setText(R.string.pull_to_refresh_pull_label);
			break;
		default:
			break;
		}
		this.mOverScrollState = state;
	}

	protected int getRefreshLayout() {
		return R.layout.include_pull_to_refresh;
	}
	
	protected int getRefreshingLayout() {
		return R.layout.include_pull_to_refreshing_header;
	}
	
	protected void setupOverscroll() {
		this.mOverScrollView = (LinearLayout) AndroidKit.getLayoutInflater()
				.inflate(getRefreshLayout(), this, false);
		this.mOverScrollTextView = (TextView) mOverScrollView
				.findViewById(R.id.refresh_tv_message);
		this.mOverscrollImage = (RotatingImageView) this.mOverScrollView
				.findViewById(R.id.refresh_iv_image);
		this.mRefreshTimeTextView = (TextView) this.mOverScrollView.findViewById(R.id.refresh_tv_time);

		setOverScrollView(mOverScrollView, HEADER_HEIGHT);
		setOverScrollListener(mOverscrollListener);
		setAutoOverScrollMultiplier(0.4F);
			
		
		LinearLayout layout = (LinearLayout) AndroidKit.getLayoutInflater().inflate(getRefreshingLayout(),this, false);
		mLoadingContainer = (LinearLayout) layout.findViewById(R.id.refresh_loading_container);
		mLoadingContainer.setVisibility(View.GONE);
		loadingImageView = (ImageView) layout.findViewById(R.id.refresh_iv_processing);
		loadingTimeTextView = (TextView) layout.findViewById(R.id.refresh_tv_time);
		lodingMessageTextView = (TextView) layout.findViewById(R.id.refresh_tv_message);
		
		addHeaderView(layout);
		setFadingEdgeColor(0);
		setFadingEdgeLength(0);
	}

	public void setLoadingViewText(int resid) {
		lodingMessageTextView.setText(resid);
	}
	
	public void dismissTip() {
		if ((this.mPullToRefreshTip != null)
				&& (this.mPullToRefreshTip.getVisibility() != View.INVISIBLE || this.mPullToRefreshTip
						.getVisibility() != View.GONE)) {
			removeHeaderView(mPullToRefreshTip);
			this.mPullToRefreshTip = null;
		}
	}

	public LinearLayout getLoadingContainer() {
		return this.mLoadingContainer;
	}

	public boolean isLoadingVisible() {
		return this.mIsLoaderVisible;
	}

	public boolean isTipAttached() {
		if (this.mPullToRefreshTip != null) {
			return true;
		}
		return false;
	}
	
	public void setLoadingVisible(boolean visibility) {
		if (mLoadingContainer != null) {
			mIsLoaderVisible = visibility;

			if (visibility) {
				mLoadingContainer.setVisibility(View.VISIBLE);
				loadingImageView.startAnimation(mRotateAnimation);
				
				if (isOverscrollPrevented() != visibility)
					setPreventOverScroll(visibility);

				setTipVisible(!visibility);
			}
			else {
				loadingImageView.clearAnimation();
				mLoadingContainer.setVisibility(View.GONE);
				if (isOverscrollPrevented() != false)
					setPreventOverScroll(false);

				setTipVisible(true);
			}
		}
	}

	/**
	 * 更新最后刷新时间
	 * @param d
	 */
	public void setLastFlushTime(Date d) {
		String time = "最后刷新时间：";
		if(d != null) {
			time = time +DateUtil.betweenWithCurDate(d);
		}
		
		mRefreshTimeTextView.setText(time);
		loadingTimeTextView.setText(time);
	}
	
	/**
	 * 不显示刷新时间
	 * @param enable
	 */
	public void setTimeEnable(boolean enable) {
		if(enable) {
			mRefreshTimeTextView.setVisibility(View.VISIBLE);
			loadingTimeTextView.setVisibility(View.VISIBLE);
		} else {
			mRefreshTimeTextView.setVisibility(View.GONE);
			loadingTimeTextView.setVisibility(View.GONE);
		}
	}
	
	public void setNoMoreRefresh(boolean paramBoolean) {
		this.mNoMoreRefresh = paramBoolean;
	}

	public void setOnPullToRefreshListener(OnPullToRefreshListener onPullToRefreshListener) {
		this.mListener = onPullToRefreshListener;
	}

	public void setTipVisible(boolean paramBoolean) {
		if (mPullToRefreshTip != null) {
			dismissTip();
		}
	}

	@Override
	public void onOverscroll(int scrollY, int scrollAmount) {
		if (overScrollPadding == 0) {
			this.overScrollPadding = AndroidKit.getPixels(30);
		}

		if (scrollY > 0) {
			if (mNoMoreRefresh)
				setOverScrollState(OS_STATE_NO_MORE_MESSAGES);
			else if (scrollY >= scrollAmount) {
				if (isBeingDragged()) {
					setOverScrollState(OS_STATE_RELEASE_TO_LOAD);
//					this.overScrollPadding = DroidKit.getPixels(30);
				}
				else {
					setOverScrollState(OS_STATE_LOADING);
				}
			} else {
				setOverScrollState(OS_STATE_PULL_DOWN_TO_LOAD);
			}
		}
		
		// overScrollPadding 就是被忽略的高度，在这个高度范围内，不旋转。
		if (scrollY > overScrollPadding && !mNoMoreRefresh) {
			// 求旋转的角度 (已拖拉的高度 / Header的总高度) 
			float f = scrollY - overScrollPadding;  
			float f1 = scrollAmount - overScrollPadding;
			int degrees = (int) (360F * f / f1 * 0.3);
			
			mOverscrollImage.setDegress(degrees);
		} else {
			mOverscrollImage.setDegress(0);
		}
	}

	@Override
	public void onRefreshRequested() {
		unlockScrolling();
		if (mListener != null && !isLoadingVisible()) {
			dismissTip();
			setLoadingVisible(true);
			mListener.onPullToRefresh();
		}
	}
	
	/**
	 * 刷新完成时调用此方法。隐藏“Loading” 控件，隐藏时将播放动画
	 */
	public void refreshComplete() {
		setLoadingVisible(false);
	}
	
	public interface OnPullToRefreshListener {
		/**
		 * 当触发下拉刷新时调用
		 */
		void onPullToRefresh();
		
		/**
		 * 当 LoadingView 被点击时调用
		 */
		void onLoadingViewClick();
	}
}